<script lang="ts" setup>
import { computed } from "vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxGroupProps,
  CheckboxOptionType,
} from "ant-design-vue"
import { CheckboxValueType } from "ant-design-vue/es/checkbox/interface"
import { useConfigContextInject } from "ant-design-vue/es/config-provider/context"
export interface CheckboxGroupExtraProps extends CheckboxGroupProps {
  divide?: boolean
}
export type Props = CheckboxGroupExtraProps

const configContext = useConfigContextInject()

// 所有已选项
const model = defineModel<CheckboxValueType[]>()

const props = withDefaults(defineProps<Props>(), {
  divide: true
})

// 从props中排除value
const computedProps = computed<Omit<Props, "value">>(() => {
  const result = { ...props }
  delete result.value
  delete result["onUpdate:value"]
  return result
})

const slots = defineSlots<InstanceType<typeof CheckboxGroup>["$slots"]>()

// 全选时CheckboxGroup的value，以优化全选时的性能
const allSelected = computed(() => {
  return props.options?.map((item) => {
    return (item as CheckboxOptionType).value
  })
})

const emit = defineEmits(["change"])

const checkedAll = computed({
  // 判断是否全部选中
  get() {
    return (
      !!model.value?.length &&
      !!props?.options?.length &&
      model.value.length === props?.options?.length
    )
  },
  // 根据是否全选设置选中项
  set(value: boolean) {
    if (value) {
      emit("change", allSelected.value)
      model.value = allSelected.value
    } else {
      emit("change", [])
      model.value = []
    }
  },
})

const indeterminate = computed(() => {
  return (
    !!model.value?.length &&
    !!props?.options?.length &&
    model.value.length < props?.options?.length
  )
})
</script>
<template>
  <div class="pc-flex pc-flex-col pc-gap-3" :class="{'pc-divide-y':computedProps.divide}">
    <div>
      <Checkbox v-model:checked="checkedAll" :indeterminate="indeterminate">
        {{ configContext.locale?.value.locale === "zh-cn" ? "全选" : "Check all"  }}
      </Checkbox>
    </div>
    <CheckboxGroup class="pc-gap-y-3 pc-grid pc-grid-cols-4 pc-gap-x-3" v-model:value="model" v-bind="computedProps">
      <template v-for="(_, key) in slots" :key="key" #[key]="params">
        <slot :key="key" :name="key" v-bind="params"></slot>
      </template>
    </CheckboxGroup>
  </div>
</template>
